<template>
	<view class="wrap">
		<view class="header">
			<g-header title="消息" :hideback="true" hideRight :rstyle="headerRightTextStyle">
				<view class="clear">清除未读</view>
			</g-header>
		</view>
		<view class="item app_flex bw" @click="onSystemTap">
			<view class="item-img">
				<image src="../../static/images/icon-msg-clock.png" mode=""></image>
			</view>
			<view class="item-R">
				<view class="item-RT app_flex-jcsb">
					<view class="item-username">系统消息</view>
					<view class="item-date">{{systemMsg.createTime || ''}}</view>
				</view>
				<view class="item-RB">
					<view class="item-msg app_ellipsis">{{systemMsg.noticeTitle || ''}}</view>
				</view>
			</view>
		</view>
		<view class="item app_flex bw" @click="onOfferMsgTap">
			<view class="item-img">
				<image src="../../static/images/icon-msg-offer.png" mode=""></image>
			</view>
			<view class="item-R">
				<view class="item-RT app_flex-jcsb">
					<view class="item-username">采购通知</view>
					<view class="item-date">{{offerMsg.createDate || ''}}</view>
				</view>
				<view class="item-RB">
					<view class="item-msg app_ellipsis">{{offerMsg.content || ''}}</view>
				</view>
			</view>
		</view>
		<view class="list bw">
			<view class="item app_flex" v-for="(item, index) in imChatList" :key="index" @click="chatPage(index)">
				<view class="item-img">
					<view v-if="item.unReadCount>0" class="unReadNum">{{item.unReadCount}}</view>
					<image
						v-if="item.customerUrl && (item.customerUrl.indexOf('http://') != -1 || item.customerUrl.indexOf('https://') != -1)"
						:src="item.customerUrl" mode=""></image>
					<image v-else :src="item.customerUrl | concatRequestUrl" mode=""></image>
				</view>
				<view class="item-M u-flex-1 app_flex-jcc">
					<view class="item-username app_ellipsis">{{item.customerName}}</view>
					<view class="item-msg app_ellipsis">
						<text v-if="item.msg.type === 'img'">[图片]</text>
						<text v-if="item.msg.type === 'audio'">[语音]</text>
						<text v-if="item.msg.data[0].data">{{item.msg.data[0].data}}</text>
					</view>
				</view>
				<view class="item-date">{{item.time}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	let WebIM = require("../../utils/WebIM")["default"];
	let disp = require("../../utils/broadcast");
	import imUtil from '../../utils/imUtil';
	import Config from '../../common/js/config'
	export default {
		data() {
			return {
				onShowCount: 0,
				headerRightTextStyle: {
					width: '140rpx',
					color: '#999',
					paddingRight: '20rpx'
				},
				imChatList: [],
				unReadSpotNum: 0,
				imChatListRes: null,
				requestUrl: Config.requestUrl,
				systemMsg: {},
				offerMsg: {}
			}
		},
		computed: {
			unReadNum() {
				let num = this.imChatList?.reduce((total, item) => {
					return total + item.unReadCount / 1
				}, 0) || '0'
				// if (num > 0) {
				// 	uni.setTabBarBadge({
				// 		index: 2,
				// 		text: num
				// 	})
				// } else {
				// 	uni.removeTabBarBadge({
				// 		index:2
				// 	})
				// }
				return num
			}
		},
		onLoad(options) {

		},
		onShow() {
			this.updatePage()
			this.getSysMsg()
			this.getOfferList()
		},
		methods: {
			updatePage() {
				// this.setImUserInfo()
				this.$store.dispatch('updateUserInfo').then(() => {
					console.log(this.gUserInfo);
					console.log(this.gShopInfo);
					// 更新店铺在环信上的用户信息
					let imToken = uni.getStorageSync('imToken')
					let imUserName = uni.getStorageSync('imUserName')
					console.log(imToken);
					console.log(imUserName);
					imUtil.loginImBytoken(imUserName, imToken)
					let avatarurl = this.gShopInfo.logoImg ? this.gShopInfo.logoImg.replace(Config.requestUrl,
						'') : ''
					imUtil.updateOwnUserInfo({
						nickname: this.gShopInfo.name,
						avatarurl: avatarurl,
						phone: this.gShopInfo.telephone,
					})
					if (this.onShowCount == 0) {
						//监听未读消息数
						disp.on("em.unreadspot", message => {
							this.getChatList();
							this.setData({
								// arr: me.getChatList(),
								unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ?
									"99+" : getApp().globalData.unReadMessageNum,
							});
						});
					}
					this.onShowCount++
					this.getChatList()
				})
			},
			/**
			 * 获取系统消息
			 */
			getSysMsg() {
				let lastReadSysMsg = uni.getStorageSync('lastReadSysMsg')
				this.$g_api.sysnoticeList({
					pageNum: 0,
					pageSize: 1
				}).then(({
					data
				}) => {
					if (data && data.rows && data.rows.length > 0) {
						this.systemMsg = data.rows[0]
					}
				})
			},
			onSystemTap() {
				uni.navigateTo({
					url: '/pages/msg/sysMsgList'
				})
			},
			getOfferList() {
				let params = {
					pageNum: 0,
					pageSize: 1
				}
				let userId = uni.getStorageSync('userId')
				if (userId) {
					params.userId = userId
				}
				this.$g_api.sysnoticeQuotedPriceList(params).then(({
					data
				}) => {
					if (data && data.rows && data.rows.length > 0) {
						this.offerMsg = data.rows[0]
					}
				})
			},
			onOfferMsgTap() {
				uni.navigateTo({
					url: '/pages/msg/offerNewsList'
				})
			},
			chatPage(index) {
				const chatItem = this.imChatList[index]
				console.log(chatItem);
				var my = uni.getStorageSync("myUsername");
				var nameList = {
					myName: my,
					your: chatItem.username,
					customerName: encodeURIComponent(chatItem.customerName),
					customerUrl: encodeURIComponent(chatItem.customerUrl),
					avatarurl: this.gShopInfo.logoImg,
					nickname: encodeURIComponent(this.gShopInfo.name)
				};
				console.log(nameList);
				uni.navigateTo({
					url: "/pages/chatroom/chatroom?username=" + JSON.stringify(nameList),
				})
			},
			// 包含陌生人版本
			getChatList() {
				console.log('msg-index.vue---getChatList');
				var myName = uni.getStorageSync("myUsername");
				console.log('myUsername-myUsername-myUsername', myName);
				var array = [];
				const me = this;
				console.log(uni.getStorageInfoSync());
				uni.getStorage({
					key: myName,
					success: (res) => {
						console.log('myUsername-myUsername-myUsername-data', res);
						let storageKeys = Object.keys(res.data);
						// let storageKeys = res.keys;
						let newChatMsgKeys = [];
						let historyChatMsgKeys = [];
						let len = myName.length;
						storageKeys.forEach((item) => {
							if (item.slice(-len) == myName && item.indexOf("rendered_") == -1) {
								newChatMsgKeys.push(item);
							} else if (
								item.slice(-len) == myName &&
								item.indexOf("rendered_") > -1
							) {
								historyChatMsgKeys.push(item);
							} else if (item === "INFORM") {
								newChatMsgKeys.push(item);
							}
						});

						cul.call(me, newChatMsgKeys, historyChatMsgKeys);
					},
					fail: (err) => {
						console.log(err);
					}
				})

				async function cul(newChatMsgKeys, historyChatMsgKeys) {
					let array = [];
					let lastChatMsg;

					for (let i = historyChatMsgKeys.length; i > 0, i--;) {
						let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
						if (index > -1) {
							let newChatMsgs = imUtil.unpackageMsgStorage(newChatMsgKeys[index]) || [];
							// let newChatMsgs = uni.getStorageSync(newChatMsgKeys[index]) || [];
							if (newChatMsgKeys.includes()) {}
							if (newChatMsgs.length) {
								lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
								lastChatMsg.unReadCount = newChatMsgs.length;
								if (lastChatMsg.unReadCount > 99) {
									lastChatMsg.unReadCount = "99+";
								}
								let dateArr = lastChatMsg.time.split(" ")[0].split("-");
								let timeArr = lastChatMsg.time.split(" ")[1].split(":");
								let month = dateArr[2] < 10 ? "0" + dateArr[2] : dateArr[2];
								lastChatMsg.dateTimeNum =
									`${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`;
								lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}:${timeArr[1]}`;
								newChatMsgKeys.splice(index, 1);
							} else {
								let historyChatMsgs = imUtil.unpackageMsgStorage(historyChatMsgKeys[i]);
								// let historyChatMsgs = uni.getStorageSync(historyChatMsgKeys[i]);
								if (historyChatMsgs.length) {
									lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
									let dateArr = lastChatMsg.time.split(" ")[0].split("-");
									let timeArr = lastChatMsg.time.split(" ")[1].split(":");
									let month = dateArr[2] < 10 ? "0" + dateArr[2] : dateArr[2];
									lastChatMsg.dateTimeNum =
										`${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`;
									lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}:${timeArr[1]}`;
								}
							}
						} else {
							let historyChatMsgs = imUtil.unpackageMsgStorage(historyChatMsgKeys[i]);
							// let historyChatMsgs = uni.getStorageSync(historyChatMsgKeys[i]);
							if (historyChatMsgs.length) {
								lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
								let dateArr = lastChatMsg.time.split(" ")[0].split("-");
								let timeArr = lastChatMsg.time.split(" ")[1].split(":");
								let month = dateArr[2] < 10 ? "0" + dateArr[2] : dateArr[2];
								lastChatMsg.dateTimeNum =
									`${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`;
								lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}:${timeArr[1]}`;
							}
						}
						if (
							lastChatMsg &&
							(lastChatMsg.chatType == "groupchat" ||
								lastChatMsg.chatType == "chatRoom")
						) {
							lastChatMsg.groupName = me.groupName[lastChatMsg.info.to];
						}
						lastChatMsg && lastChatMsg.username != myName &&
							array.push(lastChatMsg);
					}

					for (let i = newChatMsgKeys.length; i > 0, i--;) {
						let newChatMsgs = imUtil.unpackageMsgStorage(newChatMsgKeys[i]) || [];
						// let newChatMsgs = uni.getStorageSync(newChatMsgKeys[i]) || [];
						if (newChatMsgs.length) {
							lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
							lastChatMsg.unReadCount = newChatMsgs.length;
							if (lastChatMsg.unReadCount > 99) {
								lastChatMsg.unReadCount = "99+";
							}
							let dateArr = lastChatMsg.time.split(" ")[0].split("-");
							let timeArr = lastChatMsg.time.split(" ")[1].split(":");
							let month = dateArr[2] < 10 ? "0" + dateArr[2] : dateArr[2];
							lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`;
							lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}:${timeArr[1]}`;
							if (
								lastChatMsg.chatType == "groupchat" ||
								lastChatMsg.chatType == "chatRoom"
							) {
								lastChatMsg.groupName = me.groupName[lastChatMsg.info.to];
							}
							lastChatMsg.username != myName && array.push(lastChatMsg);
						}
					}

					array.sort((a, b) => {
						return b.dateTimeNum - a.dateTimeNum;
					});
					array = await this.setStoreName(array)
					this.setData({
						imChatList: array,
					});
				}
			},
			/**
			 * @description 对门店列表进行拦截,并对没有门店名称的项通过环信获取用户昵称
			 */
			setStoreName(msgList) {
				return new Promise((resolve, reject) => {
					let arr = msgList.filter(item => !item.customerName)
					let userIds = arr.map(item => {
						return item.username
					})
					imUtil.fetchUserInfoById(userIds).then(({
						data
					}) => {
						// console.log('datadata', data)
						msgList = msgList.map(item => {
							if (data[item.username]) {
								item.customerName = data[item.username].nickname
								item.customerUrl = data[item.username].avatarurl
							}
							return item
						})
						resolve(msgList)
					})
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.header {}

	.sysMsg {}

	.sysMsg-img {
		image {
			width: 90rpx;
			height: 90rpx;
		}
	}

	.sysMsg-R {}

	.sysMsg-R_title {}

	.sysMsg-R_desc {}

	.list {
		margin-top: 20rpx;
	}

	.item {
		width: 750rpx;
		padding: 24rpx 30rpx;
		box-sizing: border-box;
		border-bottom: 1px solid $g-border-color;
	}

	.item-img {
		position: relative;
		width: 90rpx;
		height: 90rpx;
		margin-right: 20rpx;
		font-size: 0;

		image {
			width: 90rpx;
			height: 90rpx;
			border-radius: 10rpx;
		}
	}

	.unReadNum {
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		width: 30rpx;
		height: 30rpx;
		line-height: 30rpx;
		text-align: center;
		background: #FF4D4D;
		border-radius: 100%;
		color: #ffffff;
		font-size: 23rpx;
		z-index: 9999;
	}

	.item-M {
		flex-direction: column;
	}

	.item-R {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.item-RB {}

	.item-username {
		max-width: 420rpx;
		font-size: 30rpx;
		margin-bottom: 4rpx;
	}

	.item-msg {
		max-width: 580rpx;
		font-size: 24rpx;
		color: #999;
	}

	.item-date {
		flex-shrink: 0;
		margin-left: 30rpx;
		font-size: 24rpx;
		color: #999;
	}
</style>